﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;

namespace TopShooter
{
	public abstract partial class UnitCommand
	{
		public class Follow : UnitCommand
		{
			public Entity TargetEntity;
			public Vector2 TargetLocation;
			public float DistanceRemaining;
			private float _timeRemaining;
			public Vector2 Direction;
			public float TargetBuffer;

			public Follow(Vector2 targetLocation)
			{
				TargetEntity = Scene.Instance.FindSelectableEntityAtLocation((int)targetLocation.X, (int)targetLocation.Y);
				
			}

			public override float TimeRemaining
			{
				get { return _timeRemaining; }
			}
			protected override void _OnStarted()
			{
				base._OnStarted();
				TargetBuffer = TargetEntity.BoundingRadius + Owner.BoundingRadius;
				_CalculateMovement();
			}
			protected override float OnUpdate(float time)
			{
				Owner.Direction = Direction;
				_CalculateMovement();
				if (time >= TimeRemaining)
				{
					_CalculateMovement();
					if (time >= TimeRemaining)
					{
						//Owner.Location = TargetLocation;
						float timeunused = time - TimeRemaining;
						_timeRemaining = 1;
						return timeunused;
					}
				}
				float adjustedSpeed = (Owner.MovementSpeed - Owner.Armor.Weight);
				if (adjustedSpeed > 0)
				{
					Vector2 offset = Direction * time * adjustedSpeed;

					Owner.Location += offset;
					_timeRemaining -= time;
					return 0;
				}
				else
					return time;
			}

			public override void Attach(Unit owner)
			{
				base.Attach(owner);
				_CalculateMovement();
			}

			private void _CalculateMovement()
			{
				TargetLocation = TargetEntity.Location;

				float dx = TargetLocation.X - Owner.Location.X;
				float dy = TargetLocation.Y - Owner.Location.Y;
				DistanceRemaining = (float)Math.Sqrt((dx * dx) + (dy * dy));
				if (DistanceRemaining == 0)
				{
					Direction = new Vector2(0, 1);
					_timeRemaining = 0;
				}
				else
				{
					Direction = new Vector2(dx / DistanceRemaining, dy / DistanceRemaining);
					DistanceRemaining -= TargetBuffer;
					float adjustedSpeed = (Owner.MovementSpeed - Owner.Armor.Weight);
					_timeRemaining = (adjustedSpeed < 0) ? 0 : DistanceRemaining / adjustedSpeed;
				}
			}
		}
	}
}
